﻿using EnvDTE;
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Windows.Forms;

namespace Inaction.UI.ComponentModel.Design
{
    public abstract class BaseTypeSelectorEditor : System.ComponentModel.Design.ObjectSelectorEditor
    {
        public BaseTypeSelectorEditor()
        {
            SubObjectSelector = true;
        }
        public override bool IsDropDownResizable
        {
            get
            {
                return true;
            }
        }

        protected static Form GetForm(IServiceProvider provider)
        {
            var components = ((System.ComponentModel.Container)(provider.GetService(typeof(System.ComponentModel.Design.IDesignerHost)))).Components;
            var enumerator = components.GetEnumerator();
            while (enumerator.MoveNext())
            {
                if (enumerator.Current is Form)
                {
                    return enumerator.Current as Form;
                }
            }
            return null;
        }
        protected IEnumerable<Assembly> GetDomainAssembies(string searchPattern = null)
        {
            var files = System.IO.Directory.GetFiles(outputPath, searchPattern);
            foreach (var file in files)
            {
                var bytes = System.IO.File.ReadAllBytes(file);
                yield return Assembly.Load(bytes);
            }
        }

        string outputPath;
        protected string GetProjectOutPutPath(IServiceProvider privider)
        {
            var dte = (EnvDTE.DTE)privider.GetService(typeof(EnvDTE.DTE));
            var p = GetActiveProject(dte);
            var temp = p.ConfigurationManager.Item(1);
            outputPath = System.IO.Path.Combine(new FileInfo(p.FullName).Directory + "\\"
                 + temp.Properties.Item("OutputPath").Value.ToString());
            outputPath = System.IO.Path.GetFullPath(outputPath);
            return outputPath;
        }

        internal static Project GetActiveProject(DTE dte)
        {
            Project activeProject = null;
            Array activeSolutionProjects = dte.ActiveSolutionProjects as Array;
            if (activeSolutionProjects != null && activeSolutionProjects.Length > 0)
            {
                activeProject = activeSolutionProjects.GetValue(0) as Project;
            }
            return activeProject;
        }

        protected virtual void FillTreeWithData(Selector selector, System.ComponentModel.ITypeDescriptorContext context, IServiceProvider provider)
        {
            base.FillTreeWithData(selector, context, provider);
            GetProjectOutPutPath(provider);
            selector.ShowLines = true;
            selector.ShowPlusMinus = true;
            selector.ShowRootLines = true;
            selector.ShowNodeToolTips = true;
        }
    }
}